﻿using Core.Common.Jwt;
using Core.Common.VierificationCode;
using Core.DTO.System.SysPerson;
using Core.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.WebApi.Controllers.SystemControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly ISysPersonService service;
        private readonly IConfiguration configuration;

        public AccountController(ISysPersonService _service, IConfiguration _configuration)
        {
            service = _service;
            configuration = _configuration;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<IActionResult> Login(LoginDTO dto)
        {
            string loginValidateCode = HttpContext.Session.GetString("LoginValidateCode");

            if (dto.VerificationCode.ToLower() != loginValidateCode.ToLower())
            {
                return BadRequest("验证码错误");
            }


            var user = await service.Login(dto.LoginName, dto.LoginPwd);
            if (user == null)
                return Content("登录名或密码错误");
            var jwtToken = new JwtHelper(configuration).GetToken(user);

            return Ok(new { user = user, token = jwtToken });
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetCode")]
        public IActionResult ValidateCode()
        {
            string code = "";
            var ms = VCodeHelper.Create(out code);
            HttpContext.Session.SetString("LoginValidateCode", code);
            return File(ms.ToArray(), @"image/png");
        }
    }
}
